
var geocoder;
var map;
var marker;

function loadMaps(){
	map = new google.maps.Map(document.getElementById("map"), {
	    center: new google.maps.LatLng(-8.067730, -34.893673),
	    zoom: 14,
	    mapTypeId: 'hybrid'
	  });
	  
	  marker = new google.maps.Marker({
	      position: new google.maps.LatLng(-8.067730, -34.893673),
	      map: map
	  });
}

//Carregamento do mapa
function load() {
	var infoWindow = new google.maps.InfoWindow;
	var input = document.getElementById('address');
	var autocomplete = new google.maps.places.Autocomplete(input);
	geocoder = new google.maps.Geocoder();
	
	loadMaps();
  	autocomplete.bindTo('bounds', map);
  
  	google.maps.event.addListener(autocomplete, 'place_changed', function() {
	  	var place = autocomplete.getPlace();

	    if (place.geometry.viewport) {
	      map.fitBounds(place.geometry.viewport);
	    } else {
	      map.setCenter(place.geometry.location);
	      map.setZoom(14);
	    }

	    marker.setPosition(place.geometry.location);
	    getLocationMarker();
	  });

  	google.maps.event.addListener(map, 'click', function(event) {
      marker.setPosition(event.latLng);
      getLocationMarker();
    });
}

/**
 * Após clica no botão esta função redireciona o mapa
 * para o local pesquisado.
 */
function codeAddress() {
        var address = document.getElementById("address").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            marker.setPosition(results[0].geometry.location);
            getLocationMarker();
          } else {
            alert("Nenhum destino encontrado com o endereço: " + address);
          }
        });
      }


/**
 * Transforma um String com a latitude juntas em 
 * duas strings contendo a lat e lng separadas.
 */
function getLocationMarker(){
    var location = marker.position;
 	var nova = ""+location;
 	
 	nova = nova.replace("(","");
 	nova = nova.replace(")","");
 	nova = nova.replace(" ", "");
 	nova.getLat();
 	nova.getLng();
    return nova;
}

/**
 * Retorna a Latitude.
 */
function getLat(){
    
	this.lat = "";
	this.test= true;
	
	for (var i=0; i < this.length; i++){
		if(this.charAt(i)==","){
			this.test=false;
			continue;
		}
			
		if(this.test)
			this.lat += this.charAt(i);
	}
	document.getElementById('lat').value=this.lat;
	return this.lat;
}

/**
 * Retorna a Longitude do marcador.
 */
function getLng(){
   
	this.lng = "";
	this.test= true;
	
	for (var i=0; i < this.length; i++){
		if(this.charAt(i)==","){
			this.test=false;
			continue;
		}
			
		if(!this.test)
			this.lng += this.charAt(i);
	}
	document.getElementById('lng').value=this.lng;
	return this.lng;
}

String.prototype.getLat = getLat;
String.prototype.getLng = getLng; 
